#include "wlist.h"

s_wlist *delete_weapon(s_wlist *wlist,
                       s_wlist *dlist)
{
  s_wlist *tmp = wlist;

  if (tmp == dlist)
  {
    wlist = wlist->next;
    free(dlist);
  }
  else
  {
    while (tmp != NULL && tmp->next != dlist)
      tmp = tmp->next;
    if (tmp->next == dlist)
    {
      tmp->next = dlist->next;
      free(dlist);
    }
  }
  return (wlist);
}

s_wlist     *add_weapon(s_weapon    *weapon,
                    s_wlist     *wlist)
{
  s_weapon	*w = init_weapon(weapon);
  s_wlist   *l = NULL;
  s_wlist   *aux = malloc(sizeof (s_wlist));

  if (wlist == NULL)
  {
    wlist = aux;
    wlist->weapon = w;
    wlist->next = NULL;
  }
  else
  {
      l = wlist;
    while (l->next != NULL)
        l = l->next;

    aux->next = NULL;
    aux->weapon = w;
    l->next = aux;
  }

  return (wlist);
}

s_wlist     *check_weapon(s_wlist *wlist)
{
  s_wlist   *tmp = wlist;

  while (tmp != NULL)
  {
    if (tmp->weapon->alive == 0)
      delete_weapon(wlist, tmp);
  }
  return (wlist);
}

s_wlist     *add_missile(s_weapon *weapon,
                         s_wlist *wlist)
{
  s_wlist   *l = NULL;
  s_wlist   *aux = malloc(sizeof (s_wlist));
  if (wlist == NULL)
  {
    wlist = aux;
    wlist->weapon = weapon;
    wlist->next = NULL;
  }
  else
  {
      l = wlist;
    while (l->next != NULL)
        l = l->next;

    aux->next = NULL;
    aux->weapon = weapon;
    l->next = aux;
  }

  return (wlist);
}

void        free_weap(s_wlist   **wlist)
{
    s_wlist *prev = NULL;
    s_wlist *p = NULL;

        if ((wlist == NULL))
            return;
        else
        {
            p = *wlist;
            prev = p;
            while (p!=NULL)
            {
                printf ("boiucle\n");
                if (p->weapon->alive == 0)
                {
                    if (p->next != NULL)
                    {
                        printf ("ahah\n");
                        prev->next = p->next;
                        free (p);
                        p = NULL;
                        p = prev->next;
                    }
                    else
                    {
                        printf("che");
                        free(p);
                        p = NULL;
                        return;
                    }
                }
                else
                {
                    printf("dans lo\n");
                    prev = p;
                    p = p->next;
                }
            }
        }
}
